package com.lyc.controller;

import com.lyc.entity.Category;
import com.lyc.entity.vo.PageBean;
import com.lyc.service.ICategoryService;
import com.lyc.utils.UUIDUtil;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @RequestMapping("/getAll")
    @ResponseBody
    public List<Category> getAll() {
        List<Category> categoryList = categoryService.getAll();
        return categoryList;
    }

    @RequestMapping("/getCategoryList")
    public String getCategoryList(Model model) {
        List<Category> categoryList = categoryService.getAll();
        model.addAttribute("categories", categoryList);
        return "/user/category_list";
    }


    @RequiresRoles("admin")
    @RequestMapping("/toAddOrUpdateCategoryPage")
    public String toAddOrUpdateCategoryPage(Integer cid, Model model) {
        if (cid != null) {
            //修改操作
            Category category = categoryService.getCategoryByCid(cid);
            model.addAttribute("category", category);
        }
        return "/admin/category_add";
    }

    @RequiresPermissions("category:addOrUpdateCategory")
    @RequestMapping("/addOrUpdateCategory")
    public String addOrUpdateCategory(Category category, MultipartFile picture, Model model, HttpServletRequest request) {
        String msg;
        try {
            if (picture != null && (picture.getOriginalFilename().endsWith(".png") || picture.getOriginalFilename().endsWith(".jpg") || picture.getOriginalFilename().endsWith(".gif"))) {
                String fileName = new String(picture.getOriginalFilename().getBytes("iso8859-1"), "utf-8");//中文转码
                String prefix = fileName.substring(fileName.lastIndexOf("."));//获取文件扩展名
                String name = UUIDUtil.getRandomFileName(prefix);
                picture.transferTo(new File(request.getServletContext().getRealPath("/static/images/cate"), name));
                File file = new File(request.getServletContext().getRealPath(category.getUrl()));
                if (file.exists())
                    file.delete();
                category.setUrl("/static/images/cate/" + name);
                if (category == null || category.getCid() == null || category.getCid() <= 0) {
                    //添加操作
                    categoryService.addCategory(category);
                }else {
                    //修改操作
                    categoryService.updateCategory(category);
                }
                return "redirect:/category/toCategoryList";
            }else if (picture==null&& !StringUtils.isEmpty(category.getUrl())){
                //如果没有上传图片且url存在路径则继续进行操作
                if (category == null || category.getCid() == null || category.getCid() <= 0) {
                    //添加操作
                    categoryService.addCategory(category);
                }else {
                    //修改操作
                    categoryService.updateCategory(category);
                }
                return "redirect:/category/toCategoryList";
            } else {
                msg = "仅支持.png/.jpg/.gif格式文件";
            }
        } catch (IOException e) {
            e.printStackTrace();
            msg = "文件上传失败";
        }
        String retUrl = request.getHeader("Referer");
        model.addAttribute("content", msg);
        model.addAttribute("url", retUrl);
        return "/common/errorModal";
    }

    @RequiresRoles("admin")
    @RequestMapping("/toCategoryList")
    public String toCategoryList(Integer currentPage, Model model) {
        if (currentPage == null || currentPage <= 0)
            currentPage = 1;
        PageBean<Category> page = categoryService.getAllByPage(currentPage);
        model.addAttribute("page", page);
        return "/admin/category_list";
    }

    @RequiresPermissions("category:deleteCategory")
    @RequestMapping("/deleteCategory")
    public String deleteCategory(HttpServletRequest request, Integer cid) {
        if (cid != null) {
            Category category = categoryService.getCategoryByCid(cid);
            File file = new File(request.getServletContext().getRealPath(category.getUrl()));
            if (file.exists())
                file.delete();
            categoryService.deleteCategoryByCid(cid);
        }
        return "redirect:/category/toCategoryList";
    }
}
